<?php

	include_once("cmsConfig.php");

	class CmsTableWriter {

		var $db;
		var $formatTable;
		var $iteratorResult;
		var $iteratorItemCount;
		var $tableInfo;
		var $fields;
		var $primaryKey;
		var $index;
		var $nonScalarColumns;
		var $binaryColumns; 

		function CmsTableWriter($formatTable, &$db){// bug format is a string that represents the cols in the db, delimeted  with a "," .. the format is started with the table name and then the cols ... there must be at least two entries .. the second col is the primary key ..

			$this->db = $db;
			$this->formatTable = $formatTable;
			$this->tableInfo = $db->getTableInfo($this->formatTable);//$db->gettableinfo($this->formatTable);

			//get the primary key.. .. this really needs to be static.. based on the table that we are dealing to..
			//otherwise every time we create one of these we run a queriy..
			if (!is_null($this->tableInfo)) {
				foreach ($this->tableInfo as $field ){
					if (stristr($field['flags'],"primary_key")){
						$this->primaryKey = $field['name'];
						break;
					}
				}
			}

			$this->begin();
		}

		function begin(){
			$this->fields = array();
			$this->iteratorResult = null;
			$this->nonScalarColumns = array();
			$this->binaryColumns = array();
		}


		function addField($name, $value, $quote = true){
			// not sure why we are not adding nulls here or not.. rather odd.
			//first check that the field name exists..
			//if (is_null($value))
			//	return true;//..;

			if (!(is_null($this->getFieldInfo($name)))){
					//value hack here
					if (preg_match('/^<<[[:space:]]*file:(.*?)>>$/', trim($value), $matches)) {
						$this->fields[$name] = trim($matches[1]);
						$this->nonScalarColumns[$name] = false;
						$this->binaryColumns[$name] = true;
					} else if( preg_match('/^<<(.*?)>>$/', trim($value), $matches) ){
						$this->fields[$name] = trim($matches[1]);
						$this->nonScalarColumns[$name] = true;
						$this->binaryColumns[$name] = false;

					}else {
						$this->fields[$name] = $value;
						$this->nonScalarColumns[$name] = false;
						$this->binaryColumns[$name] = false;
					}
							
				return true;
			}
			return false;
		}

		function newItem(){
			if(($this->db->canExecuteQueries())){
				$cols = array();
				$vals = array();
				$qs = array();
				foreach ($this->fields as $fieldName => $field){
					if (isset($field) && strlen($field) > 0 && !is_null($field)){
						array_push($cols, $fieldName);
					 	array_push($vals, $field);
					 	if ($this->nonScalarColumns[$fieldName])
					 		array_push($qs,"!");
					 	else if ($this->binaryColumns[$fieldName])
					 		array_push($qs,"&");
					 	else
					 		array_push($qs,'?');
					}
				}
				$query = "INSERT INTO " .  $this->formatTable . " (`"  .  implode("`, `",$cols) . "`) VALUES(". implode(",", $qs) .")";
//echo $query;
				if (($res = $this->db->prepareAndExecuteQuery($query,$vals))){
					return TRUE;
				}

			}
			//if we get this far some thing did not work...
			return false;
		}

		function readItem($itemID){
		
			if($this->db->canExecuteQueries()){
			
				$query="SELECT * FROM " . $this->formatTable . " WHERE " . $this->primaryKey. "=\"" . $itemID . "\"";
				$this->db->executeQuery($query);
				if(($this->db->numRows()>0)){
					return $this->db->nextObject();
			
				}
			}
			return false;
		}

		function saveItem(){
			if ($this->db->canExecuteQueries()){
				//check that we have a valid primary key...
				if ($this->fields[$this->primaryKey]){
					$cols = array();
					$vals = array();
					foreach ($this->fields as $fieldName => $field){
						if ($fieldName != $this->primaryKey){
							
						if ( @$this->nonScalarColumns[$fieldName]) //issues with this if we alter the bloody logic.. 
					 		array_push($cols,"`$fieldName`=!");
					 	else if ( @$this->binaryColumns[$fieldName]) //issues with this if we alter the bloody logic.. 
					 		array_push($cols,"`$fieldName`=&");
					 	else	
					 		array_push($cols,"`$fieldName`=?");
					 		
						array_push($vals, $field);
							
						}
					}
					array_push($vals, $this->fields[$this->primaryKey]);
					$query = "UPDATE " . $this->formatTable . " SET " . implode($cols,", ") . " WHERE `". $this->primaryKey ."`= ?";
					return $this->db->prepareAndExecuteQuery($query,$vals);
				}
			}
			return false;
		}

		function isReady(){
			if ($this->db->canExecuteQueries()){
				return TRUE;
			}
			return FALSE;
		}

		function deleteItem($itemID){
			if ($this->db->canExecuteQueries() ){
				$query="DELETE FROM ". $this->formatTable . " WHERE " . $this->primaryKey . "=\"" . $itemID . "\"";
				return $this->db->executeQuery($query);
			}
			return FALSE;
		}

		function resetIterator(){
			return $this->resetCustomIterator(" ORDER BY " . $this->primaryKey);
		}

		function resetCustomIterator($queryOpts){
		
			$query = "SELECT  $this->primaryKey FROM $this->formatTable $queryOpts";
			
			if (($this->db->canExecuteQueries()) && ($this->db->executeQuery($query))){
			
				$this->iteratorResult = $this->db->getResultSet();
				$this->iteratorItemCount = $this->db->numRows();
				
				return true;
			}
			return false;
		}

		function nextItem(){
			if(($this->db->canExecuteQueries())){

				$this->db->setResultSet($this->iteratorResult);
				$id = $this->db->nextRow();
				$this->iteratorResult = $this->db->getResultSet();
				
				if ($id && ($ret=$this->readItem($id[0]))){
				
					$this->index =$this->index + 1;
					if (CMS_QUERY_DEBUG) {
						myPrintR($ret,"RETURN DATA FROM readItem");
					} 
					return $ret;
				} else {
					return FALSE;
				}
			} else {
				return false;
			}
		}

		function getTableWriterDB(){
			return $this->db;
		}

		function getTableInfo(){
			return $this->tableInfo;
		}

		function getFieldInfo($fieldName){
			foreach ($this->tableInfo as $field ){
				if ($field['name'] == $fieldName){
					return $field;
				}
			}
			return null;
		}

		function getIteratorResultSet(){
			return $this->iteratorResult;
		}

		function setIteratorResultSet($iteratorResult){
			$this->iteratorResult = $iteratorResult;
		}



	}
?>